// pages/passage/passage.js
const QQMapWX = require("../../../utils/qqmap-wx.js");
var distance = new QQMapWX({
  key: "DN6BZ-YKMRP-EUHDE-LEBIO-YR736-SRBUI" // 必填
});

const app = getApp();
var getlist = function (that) {
  // var drivers = app.getApi.drivers;
  // var company = wx.getStorageSync("COMPANY");
  var drivers = wx.getStorageSync("DRIVERS");
  wx.showLoading({
    title: "加载中"
  });
  app.getApi.request(

    that.data.url, {
      location: {
        longitude: wx.getStorageSync("longitude"),
        latitude: wx.getStorageSync("latitude"),
        locationAddress: wx.getStorageSync("address")
      },
      driversOrdersStatus: that.data.navIndex,
      drivers: {
        id: drivers.id,
        name: drivers.name,
        tel: drivers.tel
      },
      ordersSearch: {
        IsGetGoodsInfo: true
      },
      pageIndex: that.data.pageIndex,
      pageSize: 10
    },
    "POST",
    res => {
      wx.hideLoading();
      if (res.data.responseCode == 1000) {
        //列表数据
        var ordersList = [];
        if (res.data.obj.length > 0) {
          for (let i = 0; i < res.data.obj.length; i++) {
            var orderObj = {};
            if (res.data.obj[i].orders.beginTime) {
              res.data.obj[i].orders.beginTime = res.data.obj[i].orders.beginTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].orders.endTime) {
              res.data.obj[i].orders.endTime = res.data.obj[i].orders.endTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].orders.beginTimeRang) { //修改取货时间格式
              res.data.obj[i].orders.beginTimeRang = res.data.obj[i].orders.beginTimeRang.substring(0, 11)
            }
            if (res.data.obj[i].orders.endTimeRang) { //修改送货时间格式

              res.data.obj[i].orders.endTimeRang = res.data.obj[i].orders.endTimeRang.substring(0, 11)

            }
            orderObj.id = res.data.obj[i].orders.id;
            orderObj.orderNumber = res.data.obj[i].orders.orderNumber;

            if (res.data.obj[i].orders.consignee) {
              orderObj.consigneeCity =
                res.data.obj[i].orders.consignee.consigneeCity;
            }

            orderObj.endTime = res.data.obj[i].orders.endTime;
            ordersList.push(orderObj);
          }
        }

        that.setData({
          items: that.data.items.concat(res.data.obj),
          onSh: true
        });

        if (that.data.pageIndex > 1 && res.data.obj.length == 0) {
          that.setData({
            isAll: true
          });
        }
        if (that.data.pageIndex == 1 && res.data.obj.length == 0) {
          that.setData({
            noData: true
          });
        }
      } else {
        wx.showToast({
          title: '请求失败',
          icon: 'loading',
          duration: 2000
        });
      }
      wx.stopPullDownRefresh()
      // if(res.data.)
    },
    res => {}
  );
};

var orderList = function (that) {
  //已完成的订单数据
  // var drivers = app.getApi.drivers;
  var drivers = wx.getStorageSync("DRIVERS");
  // var drivers = app.getApi.drivers;
  wx.showLoading({
    title: "加载中"
  });
  app.getApi.request(
    "/api/Orders/FinishedList", {
      driver: {
        id: drivers.id,
        name: drivers.name,
        tel: drivers.tel
      },
      location: {
        longitude: wx.getStorageSync("longitude"),
        latitude: wx.getStorageSync("latitude"),
        locationAddress: wx.getStorageSync("address")
      },
      ordersSearch: {
        IsGetGoodsInfo: true
      },
      pageIndex: that.data.pageIndex,
      pageSize: 10
    },
    "POST",
    res => {
      wx.hideLoading();
      if (res.data.responseCode == 1000) {
        //列表数据
        if (res.data.obj.length > 0) {
          for (let i = 0; i < res.data.obj.length; i++) {
            if (res.data.obj[i].beginTime) {
              res.data.obj[i].beginTime = res.data.obj[i].beginTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].endTime) {
              res.data.obj[i].endTime = res.data.obj[i].endTime.substring(5, 10).replace('-', '.')
            }

            if (res.data.obj[i].beginTimeRang) { //修改取货时间格式
              res.data.obj[i].beginTimeRang = res.data.obj[i].beginTimeRang.substring(0, 11)
            }
            if (res.data.obj[i].endTimeRang) { //修改送货时间格式

              res.data.obj[i].endTimeRang = res.data.obj[i].endTimeRang.substring(0, 11)

            }
          }
        }
        that.setData({
          items: that.data.items.concat(res.data.obj),
          onSh: true
        });

        if (that.data.pageIndex > 1 && res.data.obj.length == 0) {
          that.setData({
            isAll: true
          });
        }
        if (that.data.pageIndex == 1 && res.data.obj.length == 0) {
          that.setData({
            noData: true
          });
        }
      } else {
        wx.showToast({
          title: '请求失败',
          icon: 'loading',
          duration: 2000
        });
      }
      wx.stopPullDownRefresh()
    },
    res => {}
  );
};

Page({
  /**
   * 页面的初始数据
   */
  data: {
    navIndex: 2,
    pageIndex: 1,
    items: [],
    isAll: false,
    noData: false,
    hidden: false,
    Pullcount: 0,
    url: "api/DriversOrders/List",
    onSh: false, //首次数据加载是否完成
    takedOrderCount: '', //待取件
    pickUpedOrderCount: '', //待入库
    finishedOrderCount: '', //已完成
    isCar: false,
    isCal: false,
    id: '',
    driversordersstatusname: '',
    currIndex: 1,
    chepaihao:'',
    shouc:'',
    shoud: '',
    shous: '',
    fac:'',
    fad:'',
    fas:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {

    var drivers = wx.getStorageSync("DRIVERS");

    var that = this;
    that.setData({
      items: [],
      isAll: false,
      noData: false,
      hidden: false,
      Pullcount: 0,
      onSh: false,
      pageIndex: 1
    });
    if (that.data.navIndex == 6) {
      orderList(that);
    } else {
      getlist(that);
    }


    app.globalData.scanCodeList = []
    app.globalData.scanCodesList = []


    app.getApi.request(
      "/api/DriversOrders/Get3StatusList", {
        drivers: {
          id: drivers.id,
          name: drivers.name,
          tel: drivers.tel
        },
        location: {
          longitude: wx.getStorageSync("longitude"),
          latitude: wx.getStorageSync("latitude"),
          locationAddress: wx.getStorageSync("address")
        },
        pageIndex: that.data.pageIndex,
        pageSize: 10
      },
      "POST",
      res => {
        wx.hideLoading();
        if (res.data.responseCode == 1000) {
          //列表数据
          that.setData({
            takedOrderCount: res.data.obj.takedOrderCount,
            pickUpedOrderCount: res.data.obj.pickUpedOrderCount,
            finishedOrderCount: res.data.obj.finishedOrderCount
          })

        } else {
          wx.showToast({
            title: '请求失败',
            icon: 'loading',
            duration: 2000
          });
        }
      },
    );

  },

  onReachBottom() {
    var that = this;
    if (!that.data.isAll && that.data.Pullcount == 0 && that.data.onSh) {
      that.setData({
        pageIndex: that.data.pageIndex + 1
      });
      that.loadMore = true;
      if (that.data.navIndex == 6) {
        orderList(that);
      } else {
        getlist(that);
      }
    } else {
      that.hidden = true;
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  nav(e) { //切换tab
    var that = this,
      url = "";
    if (e.currentTarget.dataset.index == 2) {
      url = "api/DriversOrders/List";
    }
    if (e.currentTarget.dataset.index == 4) {
      url = "api/DriversOrders/List";
    }
    that.setData({
      navIndex: Number(e.currentTarget.dataset.index),
      items: [],
      url: url,
      isAll: false,
      noData: false,
      hidden: false,
      Pullcount: 0,
      pageIndex: 1
    });
    if (e.currentTarget.dataset.index == 6) {
      orderList(that);
    } else {
      getlist(that);
    }
  },
  order(e) { // 跳转取件
   var items =[]
    var item = JSON.stringify(e.currentTarget.dataset.item);
    items.push(item)
    app.globalData.driversOrders = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "../take/take?id=" +
        e.currentTarget.dataset.id +
        "&item=" +
      items
    });
  },
  deliveryDetail(e) { //派单详情

    var item = JSON.stringify(e.currentTarget.dataset.item);
    app.globalData.driversOrders = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "../deliveryDetail/deliveryDetail?id=" +
        e.currentTarget.dataset.id +
        "&item=" +
        item
    });
  },
  achieveDetails(e) { //完成订单详情
    var item = JSON.stringify(e.currentTarget.dataset.item);
    app.globalData.driversOrders = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: "../achieveDetails/achieveDetails?id=" +
        e.currentTarget.dataset.id +
        "&item=" +
        item
    });
  },
  /**
   *拨打电话
   */
  makePhoneCall(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.number
    });
  },
  toMap: function (e) {
    //进入地图页面
    let address = e.currentTarget.dataset.address;

    distance.geocoder({
      address: address,
      success: function (res) {
        if (res.result) {
          // that.setData({
          //     location: res.result
          // })
          wx.openLocation({
            latitude: parseFloat(res.result.location.lat),
            longitude: parseFloat(res.result.location.lng),
            scale: 18,
            address: address
          });
        } else {
          that.setData({
            location: null
          });
        }
      },
      fail: function (res) {

      },
      complete: function (res) {

      }
    });
  },
  onPullDownRefresh: function () {
    this.onLoad()
  },
  toSMS() { //发送短信
    wx.showToast({
      title: ' 功能正在开发',
      icon: 'loading',
      duration: 2000
    });
  },
  cal() {
    var that = this
    that.setData({
      isCal: false
    })
  },
  sub(id, driversOrdersStatusName) {
    var that = this
    var drivers = wx.getStorageSync("DRIVERS");
    var company = wx.getStorageSync("COMPANY");
    app.getApi.request(
      "/api/Vehicles/vehicledeparture", {
        drivers: {
          id: drivers.id,
          name: drivers.name,
          tel: drivers.tel
        },
        "driversOrders": {
          "id": that.data.id,
          "driversOrdersStatus": 1,
          "driversOrdersStatusName": that.data.driversOrdersStatusName,
          "pickUpNums": 0
        }

      },
      "POST",
      data => {
        var that = this
        if (data.statusCode == "200") {
          that.setData({
            isCar: true,
            isCal: false
          })
        }
      },

    );
  },
  goCar(e) { //发车
    var that = this
    that.setData({
      isCal: true,
      id: e.currentTarget.dataset.id,
      driversordersstatusname: e.currentTarget.dataset.driversordersstatusname
    })
  },
  changeCar() { //换车
    wx.navigateTo({
      url: '../myCart/myCart',
    })
  },
  toindex() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  topassage() {
    wx.redirectTo({
      url: '../passage/passage',
    })
  },


  // tab切换
  tabChange(e) {
    let _datasetId = e.target.dataset.id;
    // wx.showToast({
    //   title:'功能正在开发',
    //   icon: 'loading',
    //   duration: 2000
    // });
    if (_datasetId == 0){
      wx.showToast({
        title:'功能正在开发',
        icon: 'loading',
        duration: 2000
      });
      return false
    }
    this.setData({
      currIndex: _datasetId
    });
  },


  chepaihao(e){//装车车牌号
    var that =this
    console.log(e.detail.value)
    that.setData({
      chepaihao: e.detail.value
    })
    
  },

  shouc(e) {//收货车牌号
    var that = this
    console.log(e.detail.value)
    that.setData({
      shouc: e.detail.value
    })
  },
  shoud(e) {//收货代理商
    var that = this
    console.log(e.detail.value)
    that.setData({
      shoud: e.detail.value
    })
  },
  shous(e) {//收货收件人
    var that = this
    console.log(e.detail.value)
    that.setData({
      shous: e.detail.value
    })
  },

  fac(e) {//收货车牌号
    var that = this
    console.log(e.detail.value)
    that.setData({
      fac: e.detail.value
    })
  },
  fad(e) {//收货代理商
    var that = this
    console.log(e.detail.value)
    that.setData({
      fad: e.detail.value
    })
  },
  fas(e) {//收货收件人
    var that = this
    console.log(e.detail.value)
    that.setData({
      fas: e.detail.value
    })
  },

  bindOrder(e) {//跳转装车列表
  console.log(e)
    console.log(e.currentTarget.dataset.idx)
    if (e.currentTarget.dataset.idx==2){
      wx.navigateTo({
        url: '../carlist/carlist'
      })
    }
    if (e.currentTarget.dataset.idx == 3) {
      wx.navigateTo({
        url: '../orderclosed/orderclosed'
      })
    }
    if (e.currentTarget.dataset.idx ==4) {
      wx.navigateTo({
        url: '../orderout/orderout'
      })
    }
  },
  bindLoadCar(e) {
    console.log(e,"状态")
    console.log(e.currentTarget.dataset.idx)
    var drivers = wx.getStorageSync("DRIVERS");
    var company = app.globalData.company
    var tokenL = app.globalData.token
    var that = this
    if (e.currentTarget.dataset.idx ==2){
      if (that.data.chepaihao == '') {
        wx.showToast({
          title: '请输入车牌号',
          icon: 'loading',
          duration: 2000
        });
        return false
      }
      wx.request({
        url: app.globalData.apiServer + "/api/DriversOrders/List",
        data: {
          plateNumber: that.data.chepaihao,
          company: {
            id: company.id,
            companyName: company.company
          },
          location: {
            longitude: wx.getStorageSync("longitude"),
            latitude: wx.getStorageSync("latitude"),
            locationAddress: wx.getStorageSync("address")
          },
          driversOrdersStatus: 2,
          ordersSearch: {
            IsGetGoodsInfo: true,
            company: {
              id: company.id,
              companyName: company.company
            },
          },
          pageIndex: 1,
          pageSize: 200
        },
        method: "POST",
        header: {
          'content-type': 'application/json',
          "Authorization": "Bearer " + tokenL,
          "LoginType": 4,
         // "lsForScan":1
        },
        success: function (res) {
          if (res.data.responseCode == 1000) {
            var items = []
            var item = JSON.stringify(res.data.obj);
            wx.navigateTo({
              url: "../take/take?item=" + item+"&index="+2
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            });
          }

        }

      })
    }
    if (e.currentTarget.dataset.idx == 3) {
      if (that.data.shouc == '' && that.data.shoud == '' && that.data.shous == '') {
        wx.showToast({
          title: '输入搜索条件',
          icon: 'loading',
          duration: 2000
        });
        return false
      }

      wx.request({
        url: app.globalData.apiServer + "/api/StockIn/List",
        data: {
          plateNumber:that.data.shouc,
          partnerName:that.data.shoud,
          senderName: that.data.shous,
          company: {
            id: company.id,
            companyName: company.company
          },
          stockInStatus: 1,
          pageIndex: 1,
          pageSize: 200
        },
        method: "POST",
        header: {
          'content-type': 'application/json',
          "Authorization": "Bearer " + tokenL,
          "LoginType": 4,
         // "lsForScan": 1
        },
        success: function (res) {
          if (res.data.responseCode == 1000) {
            var items = []
            var item = JSON.stringify(res.data.obj);
            wx.navigateTo({
              url: "../take/take?item=" + item + "&index=" + 3
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            });
          }

        }

      })
    }

    if (e.currentTarget.dataset.idx == 4) {
      if (that.data.fac == '' && that.data.fad == '' && that.data.fas == '') {
        wx.showToast({
          title: '输入搜索条件',
          icon: 'loading',
          duration: 2000
        });
        return false
      }

      wx.request({
        url: app.globalData.apiServer + "/api/StockOut/List",
        data: {
          plateNumber: that.data.fac,
          partnerName: that.data.fad,
          senderName: that.data.fas,
          company: {
            id: company.id,
            companyName: company.company
          },
          stockOutStatus: 1,
          pageIndex: 1,
          pageSize: 200,
        },
        method: "POST",
        header: {
          'content-type': 'application/json',
          "Authorization": "Bearer " + tokenL,
          "LoginType": 4,
          //"lsForScan": 1
        },
        success: function (res) {
          if (res.data.responseCode == 1000) {
            var items = []
            var item = JSON.stringify(res.data.obj);
            wx.navigateTo({
              url: "../take/take?item=" + item + "&index=" + 4
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            });
          }

        }

      })
    }

  }
});